package com.usian.app.gateway.filter;

import com.usian.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Log4j2
public class AuthorizeFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();  // 获取用户的请求路径以及携带的参数
        ServerHttpResponse response = exchange.getResponse(); // 帮我们做相应到浏览器上 返还 401认证失败
        //编辑放行路径
        boolean flag = false;
        //2.判断当前的请求是否为登录，如果是，直接放行
        String[] urls ={"/register","/login/login_auth"};
        for (String url:urls){
           if( request.getURI().getPath().contains(url)){
               flag = true;
               break;
           }
        }
        if(flag){
            //放行
            return chain.filter(exchange);
        }
        //获取token
        String jwtToken =  request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(jwtToken)){
            //如果不存在，向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // jwtToken 是有值的  但是不确定是否合法
       try {
           //直接解析Token 确定合法
           Claims claims = AppJwtUtil.getClaimsBody(jwtToken);
           //直接携带token放行
           request.mutate().header("token",jwtToken);
           return chain.filter(exchange);
       }catch (Exception e){
            //如果不存在，向客户端返回错误提示信息
           response.setStatusCode(HttpStatus.UNAUTHORIZED);
           return response.setComplete();
       }
    }

    //优先级
    @Override
    public int getOrder() {
        return 0;
    }
}
